<template>
  <div>
    <van-swipe-cell v-for="item in carList" :key="item.shopCartId">
      <van-card
        :num="item.goodsCount"
        :price="item.goods.goodsPrice"
        :title="item.goods.goodsName"
        class="goods-card"
        :thumb="item.goods.goodsCoverImg"
      />
      <template #right>
        <van-button square text="删除" type="danger" class="delete-button" @click="deleteOne(item.shopCartId)" />
      </template>
    </van-swipe-cell>
    <van-submit-bar :price="total" button-text="提交订单" @submit="onSubmit" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      carList: [],
      total: 0
    }
  },
  created() {
    //根据id获取用户购物车的内容
    this.getCarListBuyUserId()
  },
  methods: {
    async getCarListBuyUserId() {
      const {data: res } =await this.$http.get('/api/cart/getAll')
      if (res.code !== 200) {
        this.$toast('购物车列表加载失败')
        return 
      }
      this.$toast('正在获取购物车列表')
      this.carList = res.data
      if(this.carList.length == 0) {return this.$toast('您的购物车为空')}
      this.carList.forEach(element => {
        this.total = this.total+ element.goodsCount*element.goods.goodsPrice
      });
      this.total = this.total*100
    },
    async deleteOne(id) {
      this.total = 0
      const {data: res } =await this.$http.post('/api/cart/deleteOneGoods', {shopCartId: id})
      if (res.code !== 200) {
        this.$toast('删除商品失败')
        return 
      }
      this.$toast('正在获取购物车列表')
      this.getCarListBuyUserId()
    },
    async onSubmit() {
      // this.$router.push({name: 'orderInfo', params:{orderList: this.carList}})
      const {data: res } =await this.$http.get('/api/order/addOrder')
      if (res.code !== 200) {
        this.$toast(res.msg)
        return 
      }
      const id = res.data
      this.$router.push({name:'pay',params:{orderId: id}})
    }
  }
}
</script>
<style lang="less" scoped>
.van-submit-bar {
  margin-bottom: 50px;
}
.goods-card {
  margin: 0;
  background-color: white;
}
.delete-button {
  height: 100%;
}
.van-swipe-cell {
  margin: 5px;
}
</style>